import { authorizedRouteHandler } from '../../../interfaces';
import log from '../../helpers/logger';
import db from '../../lib/db'
import { Router } from 'hyper-express';

const requireUser: authorizedRouteHandler = (req, res, next) => {
  log.info('[AUTH] USER CHECK REQUESTED FOR ' + req.originalUrl);
  log.info('[AUTH] USER CHECK REQUESTED FOR ' + res.locals.id);
  const id = res.locals.id;

  if (!id || !id.user || !id.session) return res.status(403).json({ err: 'not login' });
  const checkPermission = checkUserPermission(req, res, id);
  log.info('[checkUserPermission] result ');
  log.info(checkPermission);
  if (!checkPermission) return res.status(403).json({ err: 'no permission' });

  return next();
};

const checkUserPermission = async (req, res, id) => {
  log.info('[checkUserPermission] USER CHECK REQUESTED FOR id' + id);
  const body = await req.json();
  const user = res.locals.id.user ? res.locals.id.user : body.id; 
  const reqRoute = req.route.pattern;
  log.info('[checkUserPermission] USER CHECK REQUESTED FOR user' + user);
 // const router = new Router();
 // let chainable = router.route(scenario_endpoint);
  
  try {
    const uctooUserGroup = await db.user_has_group.findMany({
      where: {
        groupable_id: user,
      },
      select:{
        group_id:true
      }
    });
// 提取所有userGroupId
const userGroupIds = uctooUserGroup.map(uug => uug.group_id)
  // 查询组是否有全部权限
  const userGroupAllPermissions = await db.group_has_permission.findMany({
    where: {
      group_id: {
        in: userGroupIds,
      },
      permission_name: '/*',
    },
    select: {
      permission_name: true,
    },
  })
  log.info('[checkUserPermission] userGroupAllPermissions ');
  log.info(userGroupAllPermissions);
  if(Object.keys(userGroupAllPermissions).length !== 0){
    return true
  }
  // 根据userGroupId查询当前访问路由是否在组权限内
  const userGroupPermissions = await db.group_has_permission.findMany({
    where: {
      group_id: {
        in: userGroupIds,
      },
      permission_name: reqRoute,
    },
    select: {
      permission_name: true,
    },
  })
  log.info('[checkUserPermission] userGroupPermissions ');
  log.info(userGroupPermissions);
  if(Object.keys(userGroupPermissions).length === 0){
    return false
  }else{
    return true
  }
  } catch (e) {
    log.error(e)
    return false
  }
}

export default requireUser;
